#! /bin/sh
#
# This script is RPM-specific
# It is run at the very end of an install/upgrade of the package
# It is NOT run on removal of the package
#
# .deb: n/a
# .rpm: STEP 6 of 6

INSTALL_DIR=/opt/datadog-dogstatsd
CONFIG_DIR=/etc/datadog-dogstatsd
SERVICE_NAME=datadog-dogstatsd

# Create a symlink to the agent's binary
ln -sf $INSTALL_DIR/bin/dogstatsd /usr/bin/datadog-dogstatsd

echo "Enabling service $SERVICE_NAME"
if command -v systemctl >/dev/null 2>&1; then
    systemctl enable $SERVICE_NAME || echo "[ WARNING ]\tCannot enable $SERVICE_NAME with systemctl"
elif command -v initctl >/dev/null 2>&1; then
    # start/stop policy is already defined in the upstart job file
    :
else
    echo "[ WARNING ]\tCannot detect a supported init system. The datadog-dogstatsd package only provides service files for systemd and upstart."
fi

# TODO: Use a configcheck command on the agent to determine if it's safe to restart,
# and avoid restarting when a check conf is invalid
if [ -f "$CONFIG_DIR/dogstatsd.yaml" ]; then
    echo "(Re)starting $SERVICE_NAME now..."
    if command -v systemctl >/dev/null 2>&1; then
        systemctl restart $SERVICE_NAME || true
    elif command -v initctl >/dev/null 2>&1; then
        initctl start $SERVICE_NAME || initctl restart $SERVICE_NAME || true
    else
        echo "[ WARNING ]\tCannot detect a supported init system. The datadog-dogstatsd package only provides service files for systemd and upstart."
    fi
else
    # No dogstatsd.yaml file is present. This is probably a clean install made with the
    # step-by-step instructions/an automation tool, and the config file will be added next.
    echo "No dogstatsd.yaml file detected, not starting dogstatsd"
fi

exit 0
